package qimao.com.edu.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import qimao.com.edu.config.AppConfig;
import qimao.com.edu.entity.Author;
import qimao.com.edu.service.AuthorService;
import qimao.com.edu.service.impl.AuthorServiceImpl;

@WebServlet("/writer/regWriter.do")
@MultipartConfig
public class RegWriterServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        
        PrintWriter out = response.getWriter();
        // 前端访问的相对路径
        String headImgPath = null;
        // 文件保存路径
        Path savedFilePath = null;
        try {
            // 1. 获取表单数据
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            String writerGender = request.getParameter("writer-gender");
            String penName = request.getParameter("penName");
            String writerIntro = request.getParameter("writerIntro");
            
            // 2. 验证必填字段
            if (username == null || username.trim().isEmpty() ||
                password == null || password.trim().isEmpty() ||
                penName == null || penName.trim().isEmpty()) {
                out.println("<script>");
                out.println("alert('用户名、密码和笔名是必填项');");
                out.println("history.back();"); // 返回注册页面
                out.println("</script>");
                return;
            }
            
            
            // 3. 处理头像上传
            Part filePart = request.getPart("headImg");
            if (filePart != null && filePart.getSize() > 0) {
                // 生成唯一文件名
                String fileName = UUID.randomUUID().toString() + "_" + 
                    filePart.getSubmittedFileName();
                
                // 使用Path类构建完整路径
                Path uploadDir = Paths.get(AppConfig.UPLOAD_PATH, "authorHeadImgs");
                
                // 确保目录存在
                Files.createDirectories(uploadDir);
                
                // 构建完整文件路径
                savedFilePath = uploadDir.resolve(fileName);
                
                // 保存文件（使用Files工具类）
                try (InputStream input = filePart.getInputStream()) {
                    Files.copy(input, savedFilePath);
                }
                
                // 构建前端访问路径（使用AppConfig中的UPLOAD_URL）
                headImgPath = AppConfig.UPLOAD_URL + "authorHeadImgs/" + fileName;
                
            }
            
            // 4. 处理数据
            Author authorInfo = new Author();
            authorInfo.setUsername(username);
            authorInfo.setPassword(password);
            authorInfo.setPenName(penName);
            authorInfo.setGender(writerGender);
            authorInfo.setBio(writerIntro);
            authorInfo.setAvatar(headImgPath);
            
            //（示例：打印到控制台）
            System.out.println("注册信息：");
            System.out.println("用户名：" + username);
            System.out.println("头像路径：" + headImgPath);
            
            AuthorService as = new AuthorServiceImpl();
            
            if(as.registerAuthorInfo(authorInfo)==1) {
            	// 5. 返回成功响应
	            out.println("<script>");
	            out.println("alert('注册成功！欢迎 " + penName + "');");
	            out.println("window.location.href = 'login-writer.html';");
	            out.println("</script>");
            }else {
            	// 找到刚刚
            	if (savedFilePath != null && Files.exists(savedFilePath)) {
                    try {
                        Files.delete(savedFilePath);
                        System.out.println("已删除临时文件: " + savedFilePath);
                    } catch (IOException e) {
                        System.err.println("删除文件失败: " + savedFilePath);
                        e.printStackTrace();
                    }
                }
            	out.println("<script>alert('注册失败，请重试'); history.back();</script>");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        doPost(request, response);
    }
}